package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.article.entity.ApAuthor;
import com.heima.article.mapper.ApAuthorMapper;
import com.heima.article.service.IApAuthorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.article.dtos.AuthorDto;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP文章作者信息表 服务实现类
 * </p>
 *
 * @author heima
 * @since 2021-03-13
 */
@Service
public class ApAuthorServiceImpl extends ServiceImpl<ApAuthorMapper, ApAuthor> implements IApAuthorService {
    @Override
    public AuthorDto findByApUserId(Integer apUserId){
        //组装查询条件
        QueryWrapper<ApAuthor> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApAuthor::getUserId,apUserId);

        ApAuthor author = this.getOne(queryWrapper);
        if(author!=null){
            return BeanHelper.copyProperties(author,AuthorDto.class);
        }
        return null;
    }

    @Override
    public ApAuthor findByWmUserId(Integer wmUserId) {
        QueryWrapper<ApAuthor> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApAuthor::getWmUserId,wmUserId);
        ApAuthor apAuthor = this.getOne(queryWrapper);
        return apAuthor;
    }

    @Override
    public Integer saveAuthor(AuthorDto dto) {
        //基于App用户id查询作者
        AuthorDto authorDto = findByApUserId(dto.getUserId());
        if(authorDto!=null){
            return authorDto.getId();
        }
        //准备作者数据，执行保存
        ApAuthor apAuthor = BeanHelper.copyProperties(dto, ApAuthor.class);
        apAuthor.setCreatedTime(new Date());
        boolean b = this.save(apAuthor);
        if(!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"保存作者失败");
        }
        return apAuthor.getId();
    }
}
